<template>
	<div>
		<el-upload ref="upload" action :file-list="fileList" :auto-upload="false" :accept="accept"
			:on-remove="deleteFilex" :before-remove="beforeRemove" :on-preview="preview"
			:on-change="(file,fileList)=>{imgChangex(file,fileList)}" :limit="limit" :url="url" :size="size">
			<el-button size="mini" type="primary">点击上传</el-button>
			<div slot="tip" class="el-upload__tip" v-if="title">{{title+',上传文件最大不能超过'+size+'M'}}</div>
		</el-upload>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				fileList: [],
			}
		},
		props: ['limit', 'accept', 'url', 'title', 'size', 'img'],
		created() {
			if (this.img != null && this.img != 'undefine' && this.img != '') {
				this.fileList.push(this.img)
			}
		},
		methods: {
			preview(file) {
				window.open(file.url)
			},
			imgChangex(file, fileList) {
				if ((file.raw.size / 1024 / 1024) > this.size) {
					this.$message.error('上传文件大小不能超过 ' + this.size + 'MB!');
					fileList.pop()
					return
				} else {
					this.fileList = fileList
				}
				let form = new FormData();
				fileList.forEach(file => {
					form.append("file", file.raw);
				})
				this.$loading()
				this.$http.post(this.url, form, {
					header: {
						"Content-Type": "multipart/form-data"
					},
				}).then((res) => {
					this.$closeLoading()
					this.$emit('saveImgs', res.result.img_url)
					this.$message.success(res.msg)
				}).catch(res => {
					fileList.pop()
				})
			},
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${ file.name }？`);
			},
			deleteFilex(file, fileList) {
				this.fileList = fileList
			},
		}
	}
</script>

<style scoped>
</style>